<?php
  require_once("../includes/config.php");
  
    $length = 20;
    
    if( isset($_POST['page'])  && !empty($_POST['page'] ))
    {
      $page =  filter_var($_POST['page'], FILTER_SANITIZE_NUMBER_INT);
      $start = $page*20 - 20;
      unset($_POST['page']);
    }
    else
    {
      $start = 0;
      $page = 1;
    }
    
    $sql = "SELECT * FROM payment_vouchers WHERE owner_id= ?";
    $sqlCount = "SELECT COUNT(*) FROM payment_vouchers WHERE owner_id = ?";
	
    $binds['owner_id'] = $_SESSION['user_id'];
  
    if(!empty($_POST['from']) && !empty($_POST['to']))
    {
      $binds['from'] = $_POST['from'];
      $binds['to'] = $_POST['to'];
      $sql .= " and miladi_date between ? AND ?";
      $sqlCount .= " and miladi_date between ? AND ?";
    }
                  
    if(!empty($_POST['contract_id']) )
    {
      $binds['contract_id'] = $_POST['contract_id'];
      $sql .= " and contract_id = ?";
      $sqlCount .= " and contract_id = ?";
    }
          
    if(!empty($_POST['payment_id']))
    {
      $binds['payment_id'] = $_POST['payment_id'];
      $sql .= " and payment_id = ?";
      $sqlCount .= " and payment_id = ?";
    }
	
		if(!empty($_POST['apart_num']) )
    {
      $binds['apart_num'] = $_POST['apart_num'];
      $sql .= " and contract_id IN ( SELECT contract_id from contract_apartments WHERE apartment_id  = ( SELECT id FROM apartments WHERE apart_name = ?)  )";
      $sqlCount .= " and contract_id IN ( SELECT contract_id from contract_apartments WHERE apartment_id  = ( SELECT id FROM apartments WHERE apart_name = ?)  )";
    }

    
    if(!empty($_POST['payment_method']))
    {
      $binds['payment_method'] = $_POST['payment_method'];
      $sql .= " and paymen_method = ?";
      $sqlCount .= " and paymen_method = ?";
    }
	//getting sum applying filters without applying limits
	$total_paids = "SELECT SUM(amount) FROM (".$sql.") AS t1";
    $sql .= " LIMIT ?,?";
    $binds['start'] = $start;
    $binds['end'] = $length;
	
    $payments = query($sql,$binds);
    $sqlCount = query($sqlCount,$binds);
    $totalPaid = query($total_paids,$binds);

    $totalPages = $sqlCount[0]['COUNT(*)'];
    $total_paid = $totalPaid[0]['SUM(amount)'];
    render("payment_reports.php", array("title"=>"تقارير سندات الصرف","page"=>$page,"total_paid"=>$total_paid,"totalPages"=>$totalPages,"payments"=>$payments,"start"=>$start,"length"=>$length,"binds"=>$binds));

?>